/** 
 * Author: rebecca.younes
 */

import("email.sendEmail");

import("etherpad.helpers");
import("etherpad.log");
import("etherpad.pro.pro_accounts");
import("etherpad.pro.pro_utils");
import("etherpad.utils.*");


//----------------------------------------------------------------
// Team email interface for facilitators and admins
//----------------------------------------------------------------

/* See ideas in account_manager_control.js for how this could be 
 * improved.
 */

function onRequest() {
  var data = {},
      result = null,
      domainEditors = pro_accounts.getDomainEditors(),
      siteLink = 'http://' + pro_utils.getFullProHost();
  
  if (request.isPost) {
    result = sendTeamEmail(domainEditors, siteLink);
  }
  
  helpers.addClientVars({
    siteLink : siteLink
  })
    
  // Display the form in either case
  renderFramed('pro/send_team_email.ejs', {
    // See account_manager_control.js and new-account.ejs for how these would work.
    // We don't really need server-side error-handling for this form, though.
    // oldData: getSession().teamEmailFormData || {},
    // stringutils: stringutils,
    // errorDiv: _errorDiv,
    // messageDiv: _messageDiv
    
    editors: domainEditors,
    result: result
  });
 
  return true;
}

function sendTeamEmail(domainEditors, siteLink) {

  var recipientIds = request.params.recipients,
      subject = request.params.subject,
      message = request.params.message,
      facilitator = pro_accounts.getDomainFacilitator(),
      fromAddr = pro_utils.getEmailFromAddr(),
      recipients,
      sentTo = [],
      sentFailed = [],
      sentToList,
      sentFailedList,
      sentToFacilitator,
      status = 'success', 
      statusMessage,
      workspaceName = getWorkspaceName(),
      smtpFrom = appjet.config['smtpFrom'];

  if (typeof recipientIds === 'string') {
    recipientIds = recipientIds.split(',');
  }

  recipients = domainEditors.filter(function(editor) {
    return recipientIds.indexOf('' + editor.id) > -1;
  });
  
  if (subject.indexOf(smtpFrom) === -1) {
    subject = "[" + workspaceName + "] " + subject;
  }
  
  subject = fixChars(subject);
  message = fixChars(message);
                  
  recipients.forEach(function(recipient) { 
    try {
      sendEmail(recipient.email, fromAddr, subject, {}, message);
      sentTo.push(recipient.fullName);
    } catch (ex) {
      log.logException(ex);
      sentFailed.push(recipient.fullName);
      status = 'error';
    } 
  });
  
  sentToList = sentTo.join(', ');
  sentFailedList =  sentFailed.join(', ');

  if (status === 'success') {
    statusMessage = 'Emails sent to all recipients.'
  } else {
    statusMessage = 'Server error: ' +
                    sentTo.length ? 'Some emails could not be sent.' : 'Emails could not be sent.' +
                    ' Please try again.';
  }

  sentToFacilitator = sendFacilitatorEmail(sentToList, sentFailedList, fromAddr, subject, message, siteLink);
  
  result = {
    status : status,
    statusMessage : statusMessage,
    fromAddr : fromAddr.replace(/[<>]/g, ''),
    sentTo : sentToList,
    sentFailed : sentFailedList,
    sentToFacilitator : sentToFacilitator,
    subject : subject,
    message : message
  };

  return result;
    
}

function sendFacilitatorEmail(recipients, failedRecipients, fromAddr, teamEmailSubject, teamEmailMessage, siteLink) {
  
  var facilitator = pro_accounts.getDomainFacilitator(),
      workspaceName = getWorkspaceName(),
      subject = '[' + workspaceName + '] Group Email Sent',
      senderName = pro_accounts.isAdminSignedIn() ? 'Administrator' : facilitator.fullName,
      body;
      
  body = renderTemplateAsString('email/team_email_facilitator_copy.ejs', {
    siteLink: siteLink,
    recipientName: facilitator.fullName,
    senderName: senderName,
    recipients: recipients,
    failedRecipients: failedRecipients,
    subject: teamEmailSubject,
    message: teamEmailMessage,
    workspaceName: workspaceName,
    project: appjet.config['project']
  });

  try {
    sendEmail(facilitator.email, fromAddr, subject, {}, body);
  } catch (ex) {
    log.logException(ex);
    return false;
  }
  
  return true;
}

function fixChars(s) {
  
  // Replace smart quotes with straight quotes
  s = s.replace( /\u2018|\u2019|\u201A|\uFFFD/g, "'" );
  s = s.replace( /\u201c|\u201d|\u201e/g, '"' ); 
  
  return s;
}
